package leetcode.code0658;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public List<Integer> findClosestElements(int[] arr, int k, int x) {
		int len = arr.length;
		int l = 0, r = len - 1;
		int close = len - 1;
		while (l <= r) {
			int mid = l + ((r - l) >> 1);
			if (arr[mid] >= x) {
				close = mid;
				r = mid - 1;
			} else {
				l = mid + 1;
			}
		}
		if (close >= 1 && x - arr[close - 1] <= arr[close] - x) {
			close = close - 1;
		}
		l = close - 1;
		r = close + 1;
		int win = 1;
		while (k > win) {
			if (l == -1 || (r < len && x - arr[l] > arr[r] - x)) {
				r++;
			} else if (r == len || x - arr[l] <= arr[r] - x) {
				l--;
			}
			win++;
		}
		List<Integer> ans = new ArrayList<>();
		for (int i = l + 1; i < r; i++) {
			ans.add(arr[i]);
		}
		return ans;
	}

	@Override
	public void debug4() {
		this.findClosestElements(H.str2array3("[3,5,8,10]"), 2, 15);

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
